Ext.onReady(function() {
	
	var deptCombStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: './html/struts/DeptAction_getDeptOptions.action'}),
		reader: new Ext.data.ArrayReader({}, [
			{name: 'value'},{name: 'text'}
		])
	});
	deptCombStore.load();
	
	var editRoleUserId;
	var allRoleGrid_ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: '../basic/RoleAction/search.action'}),
		remoteSort: true,
		reader: new Ext.data.JsonReader(
			{totalProperty: 'total',idProperty:'id',root: 'invdata'},
			[
				{name: 'id'},
				{name: 'roleName'},
				{name: 'describle'},
				{name: 'defaultAction'}
			]
		)
	});
	
	var allRoleGrid_cm =  new Ext.grid.ColumnModel([
		{header:'角色名称', dataIndex:'roleName', menuDisabled:true, sortable:true}
	]);
	
	var allRoleGrid = new Ext.grid.GridPanel({
		region: 'center',
		ds: allRoleGrid_ds,
		cm: allRoleGrid_cm,
		viewConfig: {
			forceFit: true
		}
	});
	
	var role_result_store = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: '../basic/UserRoleAction/getUserRole.action'}),
		remoteSort: true,
		reader: new Ext.data.JsonReader(
			{totalProperty: 'total',idProperty:'id',root: 'invdata'},
			[
				{name: 'id'},
				{name: 'roleName'}
			]
		)
	});
	var role_result_cm = new Ext.grid.ColumnModel([
		{header:'已选择', dataIndex:'roleName', menuDisabled:true, sortable:true, width: 70}
	]);
	var role_result_grid = new Ext.grid.GridPanel({
		region: 'center',
	    store: role_result_store,
		cm: role_result_cm
	});
	
	allRoleGrid_ds.load({params: {start:0, limit:200}});
	
	var userRolePane = new Ext.Panel({
		region: 'center',
		layout:'table',
		layoutConfig: {columns:5},
		bodyStyle: "background-color:#FDFDFD; border-width: 0px 0px 0px 0px;",
		items:[
			{
		        colspan:2,
		        width:100,
		        height: 200,
		        layout:'border',
		        items:[allRoleGrid]
		    },
		     {
		    	width:50,
		    	height: 200,
		    	layout:'fit',
		        layout: {type:'vbox',padding:'5',pack:'center',align:'center'},
	            defaults:{margins:'0 0 5 0'},
				items: [
					new Ext.Button({
						text: ' >> ',
						handler: function () {
							if(allRoleGrid.getSelectionModel().hasSelection()) {
								var record = allRoleGrid.getSelectionModel().getSelected();
								var _rs = new Ext.data.Record({
									id: record.id, roleName:record.data.roleName
								}) ;
								role_result_store.add(_rs);
							}
						}
					}),
					new Ext.Button({
						text: ' << ',
						handler: function () {
							var record =role_result_grid.getSelectionModel().getSelected();
							role_result_store.remove(record);
						}
					})
				]
		    },
		    {
		        colspan:2,
		        width:100,
		        height: 200,
		        layout:'border',
		        items:[role_result_grid]
		    }
		]
	});
	
	var userRoleWin = new Ext.Window({
		title: '编辑用户角色',
		layout:'fit',
		width:300,
		height:250,
		modal : true,
		closeAction:'hide',
		plain: true,
		layout: 'border',
		items: [userRolePane],
		buttons:[
			{
				text: '保存'	,
				handler: function() {
					var roleResult = [];	
					role_result_store.each(function(rec){
				    	roleResult.push(rec.data);
				   	});
				   	var roleResultObj = Ext.util.JSON.encode(roleResult);
					Ext.Ajax.request({
						method: 'post',
						url: '../basic/UserRoleAction/saveUserRole.action',
						params: {userId: editRoleUserId, selRole: roleResultObj},
						success:function(resp){
							var obj=Ext.util.JSON.decode(resp.responseText);
							if(obj.result == 'success') {
								userRoleWin.hide();
								Ext.MessageBox.alert('提示', '保存成功！');
							}
							else {
								Ext.MessageBox.alert('出错了', '保存失败!' + obj.info);
							}
						}
					});
				}
			},
			{
				text: '取消'	,
				handler: function() {
					userRoleWin.hide();
				}
			}
		]
	});
	
	var editForm = new Ext.FormPanel({
		labelAlign: 'right',
		region: 'center',
		autoScroll:true, 
		labelWidth: 100,
		frame: true,
		xtype: 'fieldset',
		items: [
			{
				items: [
					{
						columnWidth: .01, layout: 'form',
						items: [
							{ xtype: 'hidden', name: 'id', hidden:true, hiddenLabel:true}
						]
					}
				]
			},
			{
				items: [
					{
						layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'userName', fieldLabel: '用户名称',allowBlank : false,anchor : '95%'}
						]
					},
					{
						layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'realName', fieldLabel: '真实姓名',allowBlank : false,anchor : '95%'}
						]
					},
					{
						layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'userPassword', fieldLabel: '密码',allowBlank : false,anchor : '95%'}
						]
					},
					{
						layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'userDuty', fieldLabel: '职务',anchor : '95%'}
						]
					},
					{
						layout: 'form',
						items: [
							new Ext.form.ComboBox({
		        	       		fieldLabel: '所在部门',
								name: 'deptId',
								hiddenName: 'deptId', 
								mode: 'local',
								triggerAction: 'all', 
								editable: false,
								allowBlank : true,
								valueField: 'value',
								displayField: 'text',
								anchor : '95%',
								store: deptCombStore
							})
						]
					}
				]
			}
		],
		buttons: [
			{
				text: '保存'	,
				handler: function() {
					if(!editForm.getForm().isValid())
						return;
						
					var userDeptName = editForm.getForm().findField('deptId').el.dom.value;
					editForm.form.doAction('submit', {
						url: '../basic/UserAction/save.action',
						method: 'post',
						waitTitle:'请等待',
					    waitMsg: '正在提交数据...',
						params: 'userDeptName=' + userDeptName,
						success: function(form, action) {
							if(action.result.result == 'success') {
								Ext.MessageBox.alert('提示', '保存成功!');
								form.reset();
								grid.getStore().reload();
								editWin.hide();
							}
						}
					});
				}
			},
			{
				text: '取消'	,
				handler: function() {
					editForm.form.reset();
					editWin.hide();
				}
			}
		]
	});
	
	var editWin = new Ext.Window({
		title: '编辑',
		layout:'fit',
		width:450,
		height:250,
		modal : true,
		closeAction:'hide',
		plain: true,
		layout: 'border',
		items: [editForm]
	});
	
	var searchForm = new Ext.FormPanel({
		frame: true,
		title: '查询',
		collapsible : true,
//		margins:'10 0 0 0',
		collapsed: true,
		autoHeight:true,
		collapseMode:'mini',
		region: 'north',
		labelAlign: 'right',
		items: [
			{
				layout: 'column',
				items: [
					{
						columnWidth: .33, layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'userName', fieldLabel: '用户名称',anchor : '95%'}
						]
					},
					{
						columnWidth: .33, layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'realName', fieldLabel: '真实姓名',anchor : '95%'}
						]
					},
					{
						columnWidth: .33, layout: 'form',
						items: [
							{ xtype: 'textfield', name: 'userDuty', fieldLabel: '职务',anchor : '95%'}
						]
					}
				]
			}
		],
		buttons: [
			new Ext.Button({
				text: '查询',
				width: 70,
				handler: function() {
					var fv = searchForm.getForm().getValues();
					ds.baseParams= fv;
					ds.load({params: {start:0, limit:20}});
				}
			}),
			new Ext.Button({
					text: '重置',
					width: 70,
					handler: function() {
						searchForm.form.reset();
						ds.baseParams= {};
						ds.load({params: {start:0, limit:20}});
					}
			})
		]
	});
	
	
	function editUserRole(userId) {
		editRoleUserId = userId;
		role_result_store.load({params: {userId:userId}});
		userRoleWin.show();
	}
	
	var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
	var cm = new Ext.grid.ColumnModel([
		sm,
		new Ext.grid.RowNumberer(),
		{header:'用户名称', dataIndex:'userName', sortable:true},
		{header:'真实姓名', dataIndex:'realName', sortable:true},
		{header:'职务', dataIndex:'userDuty', sortable:true},
		{header:'创建时间', dataIndex:'createTime', sortable:true},
		{header:'所在部门', dataIndex:'userDeptName', sortable:true}
	]);
	
	function renderOp(value, cellmeta, record, rowIndex, columnIndex, stor) {
		return '<ul><li>黄：AAAAAAAAAA </li><li>橙：BBBBBBBBBB</li><li>红：CCCCCCCCCC</li></ul>';
	}
	
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: '../basic/UserAction/search.action'}),
		remoteSort: true,
		reader: new Ext.data.JsonReader(
			{
				totalProperty: 'total',
				idProperty:'id',
				root: 'invdata'
			},
			[
				{name: 'id'},
				{name: 'userName'},
				{name: 'realName'},
				{name: 'userDuty'},
				{name: 'createTime'},
				{name: 'userDeptName'}
			]
		)
	});
	ds.load({params: {start:0, limit:20}});
	var grid = new Ext.grid.GridPanel({
		el: 'grid',
		region: 'center',
		ds: ds,
		cm: cm,
		sm: sm,
		viewConfig: {
			forceFit: true
		},
		tbar: new Ext.Toolbar({
			buttonAlign: 'left',
			buttons: [
				{
					text: '查询'	,
					iconCls: 'find',
					handler: function() {
						if(searchForm.collapsed)
							searchForm.expand();
						else
							searchForm.collapse();
					}
				},
				{
					text: '新增',
					iconCls: 'add',
					handler: function() {
						editForm.form.reset();
						editWin.show();
					}
				},
				{
					text: '修改'	,
					iconCls: 'edit',
					handler: function() {
						var rs = grid.getSelectionModel().getSelected();
						editForm.load({
							url: '../basic/UserAction/getDetailInfo.action',
							params: {id: rs.data.id}
						});
						editWin.show();
					}
				},
				{
					text: '角色分配'	,
					iconCls: 'edit',
					handler: function() {
						var rs = grid.getSelectionModel().getSelected();
						editUserRole(rs.data.id);
					}
				},
				{
					text: '删除'	,
					iconCls: 'del',
					handler: function() {
						var rs = grid.getSelectionModel().getSelected();
						deleteUser(rs.data.id, rs.data.userName, rs.data.realName);
					}
				}
			]
		}),
		bbar: new Ext.PagingToolbar({
			pageSize: 20,
			store: ds,
			displayInfo: true,
			displayMsg: '显示第{0}条到{1}条记录,一共{2}条',
			emptyMsg: '没有记录'
		})
	});
	
	var contextMenu = new Ext.menu.Menu({
        items: [
	        {
	            text: '修改',
	            iconCls: 'edit',
	            scope: this,
	            handler: function() {
	            	var rs = grid.getSelectionModel().getSelected();
	            	showInfo(rs.data.id);
	            }
	        },
	        {
				text: '角色分配'	,
				iconCls: 'edit',
				handler: function() {
					var rs = grid.getSelectionModel().getSelected();
					editUserRole(rs.data.id);
				}
			},
	        {
	            text: '删除',
	            iconCls: 'del',
	            scope: this,
	            handler: function() {
	            	var rs = grid.getSelectionModel().getSelected();
	            	deleteUser(rs.data.id, rs.data.userName, rs.data.realName);
	            }
	        }
		]
    });
    
    grid.on('rowcontextmenu', function(grid, index, event) {
		event.stopEvent();
		grid.getSelectionModel().selectRow(index);
		contextMenu.showAt(event.getXY());
	});
	
	
	function showInfo(id) {
		editForm.load({
			url: '../basic/UserAction/getDetailInfo.action',
			params: {id: id}
		});
		editWin.show();
	}
	
	function deleteUser(id, userName, realName) {
		if(userName == 'admin') {
			Ext.MessageBox.alert('提示', '不能删除管理员！！');
			return;
		}
		
		Ext.MessageBox.confirm('提示', '确定删除  ' + realName + ' ?', function(btn) {
			if(btn != 'yes') {
				return;
			}
			Ext.Ajax.request({
				method: 'post',
				url: '../basic/UserAction/delete.action',
				params: {id: id},
				success:function(resp){
					var obj=Ext.util.JSON.decode(resp.responseText);
					if(obj.result == 'success') {
						grid.getStore().reload();
						Ext.MessageBox.alert('提示', '删除成功！');
					}
					else {
						Ext.MessageBox.alert('出错了', '删除失败!' + obj.info);
					}
				}
			});
		});
	}
	
	new Ext.Viewport({
		layout: {
            type:'border',
            padding: 100
        },
		items:[
			searchForm,grid
		]
	});
});